package cn.anxingongyou.anxin.service.impl;

import cn.anxingongyou.anxin.entity.CommentWorker;
import cn.anxingongyou.anxin.mapper.CommentWorkerMapper;
import cn.anxingongyou.anxin.service.CommentWorkerService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommentWorkerServiceImpl implements CommentWorkerService {

    private final CommentWorkerMapper commentWorkerMapper;
    @Autowired
    public CommentWorkerServiceImpl(CommentWorkerMapper commentWorkerMapper) {
        this.commentWorkerMapper = commentWorkerMapper;
    }

    @Value("${weixin.appid}")
    private String appID;
    @Value("${weixin.appsecret}")
    private String appSecret;

    @Override
    public int insert(CommentWorker commentWorker) {
        return commentWorkerMapper.insert(commentWorker);
    }

    @Override
    public int deleteByPrimaryKey(Long id) {
        return commentWorkerMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(CommentWorker commentWorker) {
        return commentWorkerMapper.updateByPrimaryKeySelective(commentWorker);
    }

    @Override
    public CommentWorker selectOne(CommentWorker commentWorker) {
        return commentWorkerMapper.selectOne(commentWorker);
    }

    @Override
    public CommentWorker selectOneByPrimaryKey(Long id) {
        return commentWorkerMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<CommentWorker> page(int pageNum, int pageSize, CommentWorker commentWorker) {
        String orderBy = "id desc";
        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(pageNum,pageSize,orderBy);
        List<CommentWorker> list = commentWorkerMapper.select(commentWorker);
        PageInfo<CommentWorker> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<CommentWorker> search(int pageNum, int pageSize, CommentWorker commentWorker) {
        String orderBy = "id desc";
        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(pageNum,pageSize,orderBy);

        Example example = new Example(CommentWorker.class);
        Example.Criteria criteria = example.createCriteria();
        if(commentWorker.getId() != null){
            criteria.andEqualTo("id",commentWorker.getId());
        }
        if(commentWorker.getWorkerId() != null){
            criteria.andEqualTo("workerId",commentWorker.getWorkerId());
        }
        if(commentWorker.getCommentatorId() != null){
            criteria.andEqualTo("commentatorId",commentWorker.getCommentatorId());
        }
        if(commentWorker.getName() != null){
            criteria.andLike("name","%" + commentWorker.getName()+ "%");
        }
        if(commentWorker.getContent() != null){
            criteria.andLike("content","%" +  commentWorker.getContent() + "%");
        }
        List<CommentWorker> list = commentWorkerMapper.selectByExample(example);
        PageInfo<CommentWorker> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public String getToken() {
        String apiurl = "https://api.weixin.qq.com/cgi-bin/token";
        String turl = String.format(
                "%s?grant_type=client_credential&appid=%s&secret=%s", apiurl,
                appID, appSecret);
        // 创建 HttpClient 客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建 HttpGet 请求
        HttpGet httpGet = new HttpGet(turl);
        // 设置长连接
        httpGet.setHeader("Connection", "keep-alive");
        // 设置代理（模拟浏览器版本）
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        // 设置 Cookie
        httpGet.setHeader("Cookie", "UM_distinctid=16442706a09352-0376059833914f-3c604504-1fa400-16442706a0b345; CNZZDATA1262458286=1603637673-1530123020-%7C1530123020; JSESSIONID=805587506F1594AE02DC45845A7216A4");

        CloseableHttpResponse httpResponse = null;
        try {
            // 请求并获得响应结果
            httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            // 输出请求结果
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(EntityUtils.toString(httpEntity));
            JsonNode tokenNode = rootNode.path("access_token");
            return tokenNode.textValue();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 无论如何必须关闭连接
        finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    public boolean msgSecCheck(String token, String content) {
        // 创建 HttpClient 客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token="+token;
        // 创建 HttpPost 请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        // 创建 HttpPost 参数
        Map map = new HashMap<>();
        map.put("content",content);
        ObjectMapper mapper = new ObjectMapper();
        String body = "";
        try {
            body = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        CloseableHttpResponse httpResponse = null;
        try {
            // 设置 HttpPost 参数
            httpPost.setEntity(new StringEntity(body, ContentType.create("text/json", "UTF-8")));
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
//            System.out.println(EntityUtils.toString(httpEntity));
            // 输出请求结果
            JsonNode rootNode = mapper.readTree(EntityUtils.toString(httpEntity));
//            System.out.println(rootNode.asText());
            JsonNode code = rootNode.path("errcode");
            int errcode  = code.asInt();
            if(errcode == 0){
                return true;
            }else {
                return false;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 无论如何必须关闭连接
        finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
